import React from 'react'
import PropTypes from 'prop-types'
// render props 实现state 与操作 state 的逻辑的复用
export default class Mouse extends React.Component {
  state = {
    x: 0,
    y: 0
  }
  // 组件挂载完成后
  componentDidMount() {
    window.addEventListener('mousemove', this.moveHandler)
  }
  // 组件将要卸载时移除事件
  componentWillUnmount() {
    window.removeEventListener('mousemove', this.moveHandler)
  }
  // 获取鼠标移动坐标值
  moveHandler = e => {
    this.setState({
      x: e.clientX,
      y: e.clientY
    })
  }
  render() {
    console.log(this.props.children)
    return this.props.children(this.state)
  }
  // 对传入的 props 属性进行约束,避免错误的发生
  static propTypes = {
    children: PropTypes.func.isRequired
  }
}